<template>
  <div>
    <div class="topSearchE">
      <div class="topSearchELeft">
        <div>
          <P> 商品分类:</P
          ><el-select
            v-model="parentCategoryId"
            :style="{ width: '160px', marginLeft: '20px' }"
            clearable
            filterable
            placeholder="商品分类"
            @clear="ClearCategory"
          >
            <el-option
              v-for="(item, i) in goodsTypeList"
              :key="i"
              :label="item.categoryName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </div>
        <div>
          <P>名称:</P>
          <el-input
            v-model="name"
            :style="{ width: '160px', marginLeft: '20px' }"
            placeholder="名称"
          ></el-input>
        </div>
      </div>
      <div class="topSearchERight">
        <el-button
          v-model="searchShop"
          type="primary"
          :style="{ marginLeft: '20px' }"
          @click="handleSearch"
        >
          查询
        </el-button>
        <el-button
          v-model="searchShop"
          :style="{ marginLeft: '20px' }"
          @click="resettingHandle"
        >
          重置
        </el-button>
      </div>
    </div>
    <!-- 未审核 -->
    <div class="goodsselloutbox">
      <div class="SecondRow">
        <div class="SecondRowLeft">
          <el-button type="primary" @click="addgoods">添加商品</el-button>
          <el-button
            :disabled="isButtonDisabled"
            size="medium"
            @click="handleRemoved"
            >下架
          </el-button>
          <el-button
            :disabled="isButtonDisabled"
            size="medium"
            @click="handleDelete"
            >删除
          </el-button>
        </div>
        <div class="SecondRowRight">
          <el-button type="primary" plain @click="handleDownload">
            导出
          </el-button>
          <!-- <el-dropdown trigger="click" style="margin-right: 10px">
            <el-button class="el-dropdown-link">
              导出<i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu
              slot="dropdown"
              style="width: 100px; text-align: center"
            >
              <el-dropdown-item @click.native="handleDownload('all')">
                导出所有
              </el-dropdown-item>
              <el-dropdown-item @click.native="handleDownload()">
                导出选中
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown> -->
          <el-button circle icon="el-icon-refresh-right" @click="Refresh">
          </el-button>
          <!-- <el-button round size="mini" @click="addgoods">添加商品</el-button> -->
        </div>
      </div>
      <div class="DataTableDiv">
        <el-table
          v-loading="loading"
          :cell-style="{ 'text-align': 'center' }"
          :data="goodsList"
          :header-cell-style="{ 'text-align': 'center' }"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" min-width="55"></el-table-column>
          <el-table-column fixed label="排序" prop="sort" min-width="70">
            <template slot-scope="scope">
              <div class="flex-container">
                <span class="flex-item">
                  <!-- 序号 -->
                  {{ scope.$index + 1 }}
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品" prop="goodsname" min-width="350">
            <template slot-scope="scope">
              <div class="flex-container">
                <img :src="scope.row.thumb" alt="商品图片" />
                <span class="flex-item">
                  <p>{{ scope.row.name }}</p>
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="商品编码" prop="code" min-width="120">
          </el-table-column>
          <el-table-column label="价格" prop="priceCurrent" min-width="100">
            <template slot-scope="scope">
              <div class="flex-container">
                {{ scope.row.priceCurrent / 100 }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="库存" prop="stock" min-width="100">
          </el-table-column>
          <el-table-column label="销量" prop="sales" min-width="100">
          </el-table-column>
          <el-table-column label="平台审核状态" prop="ptStatus" min-width="150">
            <template slot-scope="scope">
              {{ getStatusText(scope.row.ptStatus) }}
            </template>
          </el-table-column>
          <el-table-column
            label="驳回/下架原因"
            prop="checkReason"
            min-width="220"
          >
            <template slot-scope="scope">
              {{ getReasonText(scope.row.checkReason) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" min-width="280">
            <template slot-scope="scope">
              <el-button
                size="small"
                v-show="scope.row.ptStatus === 0"
                type="text"
                @click="SubmitReview(scope.row)"
                >提交审核</el-button
              >
              <el-button
                size="small"
                type="text"
                @click="handleClick(scope.row)"
                >编辑
              </el-button>
              <el-button size="small" type="text" @click="handleDel(scope.row)"
                >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="paging">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="100"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>
    <!-- 添加/修改商品组件 -->
    <GoodesModel
      v-if="centerDialogVisible"
      :centerDialogVisible="centerDialogVisible"
      :currentRow="currentRow"
      :enterType="enterType"
      @cancelgoodesmodel="cancelgoodesmodel"
      @Refresh="Refresh"
    />
  </div>
</template>
<script>
import GoodesModel from "@/views/mall/managementend/goods/goods-manage/goodes-model.vue";
import {
  deleteGoods,
  getCategoryList,
  getGoods,
  getGoodsType,
  updateGoodsAttr,
  updateGoodsStatus,
  GoodsDetail,
  ExportData,
} from "@/api/mallApi/goodsOnsell/goodsOnsell";
import { SubmitForReview } from "@/api/mallApi/managementend/mallset";

export default {
  name: "GoodsStatus",
  components: {
    GoodesModel,
  },
  data() {
    return {
      // 添加/修改 商品弹窗
      centerDialogVisible: false,
      currentRow: {}, // 保存当前行数据
      enterType: 0, // 默认值为1，表示从编辑按钮进入
      Attributes: null, // 商品属性
      searchShop: "",
      goodsList: [],
      classShop: [],
      // 商品分类列表
      goodsTypeList: [],
      AttributesSelect: [
        { name: "推荐", value: 0 },
        { name: "新品", value: 1 },
        { name: "热卖", value: 2 },
        { name: "包邮", value: 3 },
        { name: "运费到付", value: 4 },
      ],
      Category: "", // 商品分类
      TradeName: "", // 商品名称
      selectedRows: [], // 表格 多选内容
      isButtonDisabled: false, // checkbox 联动按钮
      currentPage: 1, // 分页
      total: 0,
      pageSize: 10,
      loading: false,
      name: "",
      parentCategoryId: "",
      categoryId: "",
      ptStatus: "",
      // 商品属性列表 1：待审核2：审核通过3：驳回 4：违规下架
      goodsStatusList: [
        { name: "草稿箱", value: 0 },
        { name: "待审核", value: 1 },
        { name: "驳回", value: 3 },
        { name: "违规下架", value: 4 },
      ],
    };
  },
  computed: {
    // fifterList(){
    //   if(!this.getGoodsList){
    //     return this.getGoodsList
    //   }
    // }
    fifterdShop() {
      return this.goodsList.filter((item) => {
        return item.name.toLowerCase().includes(this.searchShop.toLowerCase);
      });
    },
  },
  watch: {
    selectedRows: {
      handler(newValue) {
        // 数组发生变化时，isButtonDisabled计算属性会重新计算，从而更新按钮的禁用状态
        this.isButtonDisabled = newValue.length === 0;
      },
      deep: true,
      immediate: true, // 立即执行处理函数
    },
  },
  created() {
    this.getGoodsTypeList();
  },
  mounted() {
    this.getAttribute();
    this.Refresh();
  },
  methods: {
    handleDownload(e) {
      this.loading = true;
      // 获取商品列表 --- 可分页
      if (this.goodsList.length === 0) {
        if (this.currentPage !== 1) this.currentPage--;
        // else return
      }
      let Status = "";
      if (!this.ptStatus) {
        Status = 100;
      }
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        isPage: 1,
        name: this.name,
        parentCategoryId: this.parentCategoryId,
        categoryId: this.categoryId,
        ptStatus: this.ptStatus ? this.ptStatus : Status,
        isDelete: 0,
        exportType: "4",
      };
      ExportData(params)
        .then((res) => {
          if (res.status !== 200) return;
          console.log("导出", res);
          const blob = new Blob([res.data], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
          });
          console.log("Blob", blob);
          const objectUrl = URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.style.display = "none";
          a.href = objectUrl; // 指定下载链接
          a.download = "未审核商品列表"; // 指定下载文件名
          a.click();
          URL.revokeObjectURL(a.href); // 释放URL对象
          console.log("objectUrl", objectUrl);
          this.loading = false;
          this.$message({
            message: "导出成功",
            type: "success",
          });
        })
        .catch((error) => {
          this.loading = false;
        });
      console.log(e);
    },
    resettingHandle() {
      this.parentCategoryId = null;
      this.name = null;
      this.refresh();
    },
    SubmitReview(e) {
      this.$confirm("是否将该商品提交审核？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const params = {
            goodsId: e.id,
            ptStatus: 1,
            reason: "",
          };
          SubmitForReview(params).then((res) => {
            if (res.code === "00000") {
              this.Refresh();
              this.$message({
                message: "提交审核成功！",
                type: "success",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    Refresh() {
      this.getGoodsList();
    },
    getStatusText(ptStatus) {
      switch (ptStatus) {
        case 0:
          return "草稿箱";
        case 1:
          return "待审核";
        case 2:
          return "审核通过";
        case 3:
          return "驳回";
        case 4:
          return "违规下架";
        default:
          return "未知状态";
      }
    },
    getReasonText(Reason) {
      switch (Reason) {
        case null:
          return "暂无原因";
        case "":
          return "暂无原因";
        default:
          return Reason;
      }
    },
    ClearAttributes() {}, // 清空 商品属性
    ClearCategory() {}, // 清空 商品分类
    // handleClick(row) {
    // },//编辑 行
    // 分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.getGoodsList();
    },
    handleCurrentChange(val) {
      // 分页
      this.currentPage = val;
      this.getGoodsList();
    },
    // 属性的多选框 点击事件请求
    changeAttHandle(item, goods) {
      let c = goods.attributes;
      const checkList = c.split(",");
      let val = "";
      this.classShop.forEach((i) => {
        if (i.value == item) {
          val = i.code;
        }
      });
      let boolean = false;
      let ind = 0;
      checkList.forEach((i, index) => {
        if (i == val) {
          boolean = true;
          ind = index;
        }
      });
      if (boolean) {
        let z = "";
        checkList.splice(ind, 1);
        checkList.forEach((i) => {
          z = `${z},${i}`;
        });
        c = z;
      } else {
        c = `${c},${val}`;
      }
      const data = {
        goodsId: goods.id,
        attributes: c,
      };
      updateGoodsAttr(data).then((res) => {
        if (res.success) {
          this.getGoodsList();
        }
      });
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection;
      // TODO 在这里进行相应的操作，如发起请求等
    }, // 表格多选
    async handleClick(row) {
      try {
        const param = {
          goodsId: row.id,
        };
        // 调用 GoodsDetail 函数，并等待其完成
        //console.log("param", param);
        //console.log("编辑接口调用1");
        this.loading = true;
        const res = await GoodsDetail(param);
        // console.log('res',res);
        this.loading = false;
        //console.log("编辑接口调用2");
        res.data.goods.priceCurrent = res.data.goods.priceCurrent / 100; //价格
        res.data.goods.price = res.data.goods.price / 100; //原价
        res.data.goods.priceCost = res.data.goods.priceCost / 100; //成本
        res.data.goods.priceStamp = res.data.goods.priceStamp / 100; //满额
        res.data.goods.postage = res.data.goods.postage / 100; //运费

        if (res.data.specItemAttrList && res.data.specItemAttrList.length > 0) {
          res.data.specItemAttrList = res.data.specItemAttrList.map((item) => {
            return {
              ...item,
              price: item.price / 100,
              priceOriginal: item.priceOriginal / 100,
              priceCost: item.priceCost / 100,
            };
          });
        }

        // 在这里可以继续处理 GoodsDetail 函数的返回值
        this.currentRow = res.data;
        //console.log("点击编辑按钮", res.data);

        // 执行下面的逻辑
        this.enterType = 2;
        this.centerDialogVisible = true; // 打开弹窗
      } catch (error) {
        // 处理错误
        console.error("处理错误", error);
      }
    },
    cancelgoodesmodel(data) {
      // 弹窗关闭时触发，可以在这里重置数据或进行其他操作
      this.currentRow = {};
      this.centerDialogVisible = data;
      this.enterType = 0;
    },
    addgoods() {
      this.enterType = 1;
      this.centerDialogVisible = true; // 打开弹窗
    }, // 添加商品
    // 获取商品列表
    getGoodsList() {
      this.loading = true;

      // 获取商品列表 --- 可分页
      let Status = "";
      if (!this.ptStatus) {
        Status = 100;
      }
      const params = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        isPage: 1,
        name: this.name,
        parentCategoryId: this.parentCategoryId,
        categoryId: this.categoryId,
        ptStatus: this.ptStatus ? this.ptStatus : Status,
        isDelete: 0,
      };
      getGoods(params)
        .then((res) => {
          if (res.code !== "00000") return;
          this.goodsList = res.data.list;
          this.total = parseInt(res.data.total);
          const attrList = [];
          this.classShop.forEach((item) => {
            attrList.push(item.value);
          });
          this.goodsList.forEach((item) => {
            item.attrList = attrList;
            const checkAttrList = [];
            const c = item.attributes;

            const checkList = c.split(",");

            this.classShop.forEach((item) => {
              const { code } = item;
              checkList.forEach((i) => {
                if (i == code) {
                  checkAttrList.push(item.value);
                }
              });
            });
            item.checkAttrList = checkAttrList;
          });
          this.loading = false;
        })
        .catch((error) => {
          this.loading = false;
        });
    },
    // 获取商品属性
    getAttribute() {
      getGoodsType({ dictionaryType: "goods_attributes" }).then((res) => {
        this.classShop = res.data;
        // this.getGoodsList();
      });
    },
    // 更改商品状态
    handleSwitchChange(row) {
      const ruleForm = {
        ids: [],
      };
      ruleForm.ids.push(row.id);
      // ruleForm.id = row.id
      ruleForm.status = row.status == 1 ? 2 : 1;
      updateGoodsStatus(ruleForm).then((res) => {
        this.getGoodsList();
      });
    },
    // 获取商品分类列表
    getGoodsTypeList() {
      getCategoryList().then((res) => {
        if (res.code === "00000") {
          this.goodsTypeList = res.data;
        }
      });
    },
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.getGoodsList();
    },
    handleDelete() {
      this.$confirm("是否删除选中商品信息?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 筛选this.selectedRows中的 id，只把id放入ids数组
          const ids = [];
          this.selectedRows.forEach((item) => {
            ids.push(item.id);
          });
          deleteGoods({ ids, isDelete: 1 }).then((res) => {
            if (res.code !== "00000") return;
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.getGoodsList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleDel(val) {
      this.$confirm("是否删除该商品信息？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const ids = [];
          ids.push(val.id);
          deleteGoods({ ids, isDelete: 1 }).then((res) => {
            if (res.code === "00000") {
              this.$message({
                message: "删除成功",
                type: "success",
              });
              this.getGoodsList();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleRemoved() {
      // // 根据this.selectedRows的中的 status，只把status不为1的id放入ids数组
      this.ids = [];
      this.selectedRows.forEach((item) => {
        if (item.status === 1) {
          this.ids.push(item.id);
        }
      });
      if (this.ids.length === 0) {
        this.$message({
          message: "请选择未下架商品",
          type: "warning",
        });
        return;
      }
      const ruleForm = {
        ids: this.ids,
      };
      ruleForm.status = 2;
      updateGoodsStatus(ruleForm).then((res) => {
        if (res.code !== "00000") return;
        this.$message({
          message: "上架成功",
          type: "success",
        });
        this.getGoodsList();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.topSearchE {
  width: 98%;
  margin: 1%;
  background-color: #fff;
  min-height: 65px;
  display: flex;
  justify-content: space-between;
  .topSearchELeft {
    width: 1050px;
    display: flex;
    margin-top: 7px;
    > div {
      margin-left: 10px;
      display: flex;
      align-items: center;
      p {
        font-size: 14px;
      }
    }
  }
  .topSearchERight {
    margin-top: 15px;
    margin-right: 30px;
  }
}
.goodsselloutbox {
  // display: flex;
  // flex-direction: column;
  // align-content: center;
  // justify-content: center;
  width: 98%;
  min-height: 750px;
  margin-top: 1%;
  margin-bottom: 1%;
  margin-left: 1%;
  background-color: #fff;
  overflow: hidden;

  .SecondRow {
    width: 100%;
    min-height: 65px;
    margin-top: 10px;
    display: flex;
    justify-content: space-between;
    .SecondRowLeft {
      margin-top: 10px;
      margin-left: 30px;
    }
    .SecondRowRight {
      margin-top: 10px;
      margin-right: 30px;
    }
  }

  .DataTableDiv {
    width: 98%;
    margin-left: 1%;
    margin-bottom: 15px;
    border: 1px solid #dcdee2;

    //表格
    .flex-container {
      display: flex;
      align-items: center; /* 垂直居中 */
      justify-content: space-around;

      > img {
        width: 60px;
        height: 60px;
      }

      .flex-item {
        width: 150px;
        height: 40px;
        -webkit-line-clamp: 2; /* 显示两行文本 */
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
    }

    .TableAttrTem {
      display: flex;
      align-items: center;
      // justify-content: space-around;
      margin: 0 25px;
    }
  }

  .paging {
    width: 99%;
    height: 50px;
    margin-bottom: 20px;
    // background-color: antiquewhite;
    display: flex;
    align-items: end;
    justify-content: end;
  }
}
</style>
